package com.mlk.engUser.service.impl;

import cn.hutool.core.util.IdUtil;
import com.github.binarywang.wxpay.bean.entpay.EntPayRequest;
import com.github.binarywang.wxpay.bean.entpay.EntPayResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.mlk.constant.EngConstant;
import com.mlk.core.component.page.Page;
import com.mlk.core.component.page.Pager;
import com.mlk.core.exception.GlobalException;
import com.mlk.core.util.IPUtils;
import com.mlk.core.util.ServerResponse;
import com.mlk.core.util.SessionUtils;
import com.mlk.core.util.SpringUtils;
import com.mlk.engUser.mapper.EngUserMapper;
import com.mlk.engUser.mapper.EngUserOutRemainMapper;
import com.mlk.engUser.mapper.EngUserRemainVerifyMapper;
import com.mlk.engUser.po.EngUser;
import com.mlk.engUser.po.EngUserOutRemain;
import com.mlk.engUser.po.EngUserRemainVerify;
import com.mlk.engUser.service.EngUserRemainVerifyService;
import com.mlk.engUser.vo.EngUserRemainVerifyVO;
import com.mlk.wx.WxPayProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

@Service
@Slf4j
public class EngUserRemainVerifyServiceImpl implements EngUserRemainVerifyService {

    @Resource
    private EngUserRemainVerifyMapper engUserRemainVerifyMapper;

    @Resource
    private EngUserMapper engUserMapper;

    @Resource
    private EngUserOutRemainMapper engUserOutRemainMapper;

    /**
     * 分页数据查询
     * @param verify
     * @return
     */
    @Page
    @Override
    public Pager listPage(EngUserRemainVerifyVO verify) {
        return Pager.adapt(this.engUserRemainVerifyMapper.selectForPage((verify)));
    }


    @Resource
    private WxPayProperties properties;

    /**
     * 审核通过
     * @param id
     * @return
     */
    @Override
    @Transactional
    public ServerResponse verifyOK(Integer id) {
        EngUserRemainVerify verify = this.engUserRemainVerifyMapper.selectById(id);

        // 查询客户信息
        EngUser user = this.engUserMapper.selectOne(EngUser.builder().openId(verify.getOpenId()).build());
        // 判断是否可以转账
        if(user.getRemain().doubleValue() < verify.getAmount().doubleValue()){
            throw new GlobalException("用户的余额不足,无法支付");
        }
        int count = 0;
        // 开始进行转账服务

        //TODO 微信转账服务
        EntPayRequest request = new EntPayRequest();
        request.setMchAppid(properties.getAppId());
        request.setMchId(properties.getMchId());
        // 这个写死就好了-- 需要是随机的---咱们没有退款的功能...
        request.setPartnerTradeNo(String.valueOf(IdUtil.createSnowflake(3L,3L).nextId()));
        request.setOpenid(user.getOpenId()); // openId
        request.setCheckName("NO_CHECK");
        // 转换到int值
        request.setAmount((int)(verify.getAmount().doubleValue()*100));
        // 测试环境下 就支付三毛钱
        // request.setAmount(30);
        request.setDescription("能源宝提现");
        request.setSpbillCreateIp(IPUtils.getInstance().getIpAddr());

        EntPayResult entPayResult =null;
        try {
          entPayResult = SpringUtils.getBean(WxPayService.class).getEntPayService().entPay(request);
        } catch (WxPayException e) {
            log.error("微信转账失败",e);
            throw new GlobalException("微信转账失败:"+e.getErrCodeDes());
        }

        // 必须这两个字段同时返回SUCCESS
        if((!StringUtils.equals(entPayResult.getErrCode(),"SUCCESS")) || (!StringUtils.equals(entPayResult.getResultCode(),"SUCCESS"))){
           throw new GlobalException("微信支付出现错误"+entPayResult);
        }

        // 下面进行业务的处理
        // 将客户的余额减去
        count = this.engUserMapper.addRemain(verify.getOpenId(),verify.getAmount().negate());
        if(count == 0){
            throw new GlobalException("操作失败");
        }

        // 修改申请单的状态
        EngUserRemainVerify temp = new EngUserRemainVerify();
        temp.setId(id);
        temp.setVerifyName(SessionUtils.getUser().getSysUser().getName());
        temp.setVerifyTime(new Date());
        temp.setStatus(2); // 2表示成功
        count = this.engUserRemainVerifyMapper.updateById(temp);
        if(count == 0){
            throw new GlobalException("操作失败");
        }
        // 填写余额减少的记录
        EngUserOutRemain  outRemain = new EngUserOutRemain ();
        outRemain.setOpenId(verify.getOpenId());
        outRemain.setCreateTime(new Date());
        outRemain.setAmount(verify.getAmount());
        outRemain.setType(EngConstant.OUT_REMAIN_TARGET.OUT_REMAIN);
        count  = this.engUserOutRemainMapper.insert(outRemain);
        if(count == 0){
            throw new GlobalException("提现失败");
        }
        return ServerResponse.ok("操作成功");
    }

    /**
     * 审核驳回
     * @param id
     * @return
     */
    @Override
    @Transactional
    public ServerResponse verifyFail(Integer id) {
        EngUserRemainVerify temp = new EngUserRemainVerify();
        temp.setId(id);
        temp.setVerifyName(SessionUtils.getUser().getSysUser().getName());
        temp.setVerifyTime(new Date());
        temp.setStatus(3); // 2表示成功
        int count = this.engUserRemainVerifyMapper.updateById(temp);
        if(count == 0){
            throw new GlobalException("操作失败");
        }
        return ServerResponse.ok("操作成功");
    }
}
